package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.event.CacheLabelEvent;
import org.dromara.common.core.service.ComboboxService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.system.domain.SysCacheLabel;
import org.dromara.system.domain.SysCombobox;
import org.dromara.system.domain.bo.SysComboboxBo;
import org.dromara.system.domain.vo.SysComboboxVo;
import org.dromara.system.mapper.SysCacheLabelMapper;
import org.dromara.system.mapper.SysComboboxMapper;
import org.dromara.system.service.ISysComboboxService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 下拉框键值Service业务层处理
 *
 * @author Lion Li
 * @date 2024-12-13
 */
@RequiredArgsConstructor
@Service
public class SysComboboxServiceImpl implements ISysComboboxService, ComboboxService {

    private final SysComboboxMapper baseMapper;
    private final SysCacheLabelMapper cacheLabelMapper;
    private final ApplicationEventPublisher applicationEventPublisher;

    /**
     * 查询下拉框键值
     *
     * @param id 主键
     * @return 下拉框键值
     */
    @Override
    public SysComboboxVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public void syncLabelCache(String cacheName, String keyFieldValue) {
        cacheLabelMapper.delete(Wrappers.lambdaQuery(SysCacheLabel.class)
            .eq(SysCacheLabel::getCacheName, cacheName)
            .eq(SysCacheLabel::getKeyFieldValue, keyFieldValue));
    }

    @Override
    public void syncLabelCache(String cacheName, String parentKeyField, String keyField, String valueField,
                               String parentKeyFieldValue, String keyFieldValue, String valueFieldValue) {
        SysCacheLabel cacheLabel = SysCacheLabel.builder()
            .cacheName(cacheName)
            .parentKey(parentKeyField)
            .keyField(keyField)
            .valueField(valueField)
            .parentKeyValue(parentKeyFieldValue)
            .keyFieldValue(keyFieldValue)
            .valueFieldValue(valueFieldValue).build();
        SysCacheLabel tmp = cacheLabelMapper.selectOne(new LambdaQueryWrapper<SysCacheLabel>()
            .eq(SysCacheLabel::getCacheName, cacheName)
            .eq(SysCacheLabel::getParentKeyValue, parentKeyFieldValue)
            .eq(SysCacheLabel::getKeyFieldValue, keyFieldValue));
        if (tmp != null) {
            cacheLabel.setId(tmp.getId());
        }
        cacheLabelMapper.insertOrUpdate(cacheLabel);
    }

    @Override
    public String queryLabel(String cacheName, String key) {
        String result = CacheUtils.get(cacheName, key);
        if (StringUtils.isBlank(result)) {
            SysCacheLabel tmp = cacheLabelMapper.selectOne(new LambdaQueryWrapper<SysCacheLabel>()
                .eq(SysCacheLabel::getCacheName, cacheName)
                .eq(SysCacheLabel::getKeyFieldValue, key));
            result = tmp == null ? null : tmp.getValueFieldValue();
        }
        return result;
    }

    @Override
    public String queryLabels(String cacheName, String keys) {
        if (StringUtils.isBlank(keys) || "null".equals(keys)) return "";
        Map<Object, Object> cacheMap = CacheUtils.getAll(cacheName);
        return JsonUtils.parseArray(keys, String.class).stream()
            .filter(cacheMap::containsKey)
            .map(key -> {
                String r = cacheMap.get(key).toString();
                if (StringUtils.isBlank(r)) {
                    r = cacheLabelMapper.selectOne(new LambdaQueryWrapper<SysCacheLabel>()
                        .eq(SysCacheLabel::getCacheName, cacheName)
                        .eq(SysCacheLabel::getKeyFieldValue, key)).getValueFieldValue();
                }
                return r;
            })
            .collect(Collectors.joining(","));
    }

    @Override
    public Map<Object, Object> queryCombobox(String cacheKey) {
        return CacheUtils.getAll(CacheNames.COMBOBOX + cacheKey);
    }

    @Override
    public Map<Object, Object> queryComboboxChildren(String cacheName, String parentKey) {
        return CacheUtils.getAll(CacheNames.COMBOBOX + cacheName + ":" + parentKey);
    }

    /**
     * 分页查询下拉框键值列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 下拉框键值分页列表
     */
    @Override
    public TableDataInfo<SysComboboxVo> queryPageList(SysComboboxBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysCombobox> lqw = buildQueryWrapper(bo);
        Page<SysComboboxVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的下拉框键值列表
     *
     * @param bo 查询条件
     * @return 下拉框键值列表
     */
    @Override
    public List<SysComboboxVo> queryList(SysComboboxBo bo) {
        LambdaQueryWrapper<SysCombobox> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysCombobox> buildQueryWrapper(SysComboboxBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysCombobox> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCacheKey()), SysCombobox::getCacheKey, bo.getCacheKey());
        lqw.eq(StringUtils.isNotBlank(bo.getKeyField()), SysCombobox::getKeyField, bo.getKeyField());
        lqw.eq(StringUtils.isNotBlank(bo.getValueField()), SysCombobox::getValueField, bo.getValueField());
        lqw.eq(StringUtils.isNotBlank(bo.getComboboxValue()), SysCombobox::getComboboxValue, bo.getComboboxValue());
        lqw.eq(StringUtils.isNotBlank(bo.getComboboxLabel()), SysCombobox::getComboboxLabel, bo.getComboboxLabel());
        return lqw;
    }

    /**
     * 新增下拉框键值
     *
     * @param bo 下拉框键值
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysComboboxBo bo) {
        SysCombobox add = MapstructUtils.convert(bo, SysCombobox.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改下拉框键值
     *
     * @param bo 下拉框键值
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysComboboxBo bo) {
        SysCombobox update = MapstructUtils.convert(bo, SysCombobox.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysCombobox entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除下拉框键值信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 发布同步缓存事件，如果为空则同步所有缓存
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     */
    private void publishCustomEvent(String cacheName, String key) {
        CacheLabelEvent customEvent = new CacheLabelEvent(this, cacheName, key);
        applicationEventPublisher.publishEvent(customEvent);
    }
}
